<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { deepClone, arr2Tree } from '@/utils'
import {
  findGroups,
  insertGroup,
  updateGroup,
  deleteGroup,
  findCams,
  insertCam,
  updateCam,
  deleteCam
} from '@/api/webCam'
import SytTable from '@/components/SytTable/SytTable.vue'
import { ElMessage } from 'element-plus'

// 分组
const groupDataRaw = () => ({
  name: '',
  pid: ''
})
const groupsData = ref([])
const groupDialogData = ref(groupDataRaw())
const groupDialogFormVisible = ref(false)
const groupDialogOpenType = ref('')
const groupRuleFormRef = ref()

const groupRules = ref({
  name: [
    {
      required: true,
      message: '请输入分组名',
      trigger: 'blur'
    }
  ]
})

const openGroupDialog = (data?) => {
  if (data) {
    groupDialogData.value = data
    groupDialogOpenType.value = '编辑'
  } else {
    groupDialogData.value = groupDataRaw()
    groupDialogOpenType.value = '添加'
  }
  groupDialogFormVisible.value = true
}

const getGroups = () => {
  findGroups().then((res) => {
    if (res.code === 200) groupsData.value = arr2Tree(res.data)
  })
  loading.value = false
}

const setGroup = async (data) => {
  if (groupDialogOpenType.value === '添加') await insertGroup(data)
  else if (groupDialogOpenType.value === '编辑') await updateGroup(data)
  getGroups()
}

const removeGroup = async (item) => {
  await deleteGroup({
    id: item.id
  })

  for (let i = 0; i < item.children.length; i++) {
    await removeGroup(item.children[i])
  }

  getGroups()
}

const groupSubmitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      setGroup(groupDialogData.value)

      groupDialogFormVisible.value = false
    } else {
      console.log('验证失败!')
      return false
    }
  })
}

let tableThs = ref([
  { title: '设备名', dataIndex: 'name' },
  { title: '摄像机品牌', dataIndex: 'brandName' },
  { title: '分组', dataIndex: 'groupName' },
  { title: '摄像机ip地址', dataIndex: 'camIp' },
  { title: '摄像机账号', dataIndex: 'camUsername' },
  { title: '摄像机通道', dataIndex: 'camChannel' },
  { title: '摄像机码流', dataIndex: 'camSubtypeName' },
  { title: '录像机ip地址', dataIndex: 'nvrIp' },
  { title: '录像机账号', dataIndex: 'nvrUsername' },
  { title: '录像机通道', dataIndex: 'nvrChannel' },
  { title: '录像机码流', dataIndex: 'nvrSubtypeName' }
])
let tableData = ref([])
let loading = ref(true)

let dialogFormVisible = ref(false)
let ruleFormRef = ref(null)
let dialogOpenType = ref('')
const rules = ref({
  name: [
    {
      required: true,
      message: '请输入设备名',
      trigger: 'blur'
    }
  ],
  brand: [
    {
      required: true,
      message: '摄像机品牌',
      trigger: 'blur'
    }
  ],
  group: [
    {
      required: true,
      message: '分组',
      trigger: 'blur'
    }
  ],
  camIp: [
    {
      required: true,
      message: '摄像机ip地址',
      trigger: 'blur'
    }
  ],
  camUsername: [
    {
      required: true,
      message: '请输入摄像机用户名',
      trigger: 'blur'
    }
  ],
  camPassword: [
    {
      required: true,
      message: '请输入摄像机密码',
      trigger: 'blur'
    }
  ],
  camChannel: [
    {
      required: true,
      message: '请输入摄像机通道',
      trigger: 'blur'
    }
  ],
  camSubtype: [
    {
      required: true,
      message: '请输入摄像机码流',
      trigger: 'blur'
    }
  ],
  nvrIp: [
    {
      required: false,
      message: '请输入录像机ip',
      trigger: 'blur'
    }
  ],
  nvrUsername: [
    {
      required: false,
      message: '请输入录像机账号',
      trigger: 'blur'
    }
  ],
  nvrPassword: [
    {
      required: false,
      message: '请输入录像机密码',
      trigger: 'blur'
    }
  ],
  nvrChannel: [
    {
      required: false,
      message: '请输入录像机通道',
      trigger: 'blur'
    }
  ],
  nvrSubtype: [
    {
      required: false,
      message: '请输入录像机码流',
      trigger: 'blur'
    }
  ]
})

//dialog data
let dialogDataRaw = () => ({
  name: '',
  brand: 0,
  group: '',
  camIp: '',
  camUsername: '',
  camPassword: '',
  camChannel: 1,
  camSubtype: 1,
  nvrIp: '',
  nvrUsername: '',
  nvrPassword: '',
  nvrChannel: 1,
  nvrSubtype: 1
})

let dialogData = ref(dialogDataRaw())

let brandOptions = ref([
  {
    label: '海康',
    value: 0
  }
])

let subtypeOptions = ref([
  {
    label: '主码流',
    value: 1
  },
  {
    label: '子码流',
    value: 2
  },
  {
    label: '第三码流',
    value: 3
  }
])

const openDialogByInsert = () => {
  dialogOpenType.value = '添加'
  dialogFormVisible.value = true

  dialogData.value = dialogDataRaw()
}

const openDialogByEdit = (row) => {
  dialogOpenType.value = '编辑'
  dialogFormVisible.value = true
  dialogData.value = deepClone(row)
}

const getCams = () => {
  findCams().then((res) => {
    if (res.code === 200)
      tableData.value = res.data.map((r) => {
        r.brandName = brandOptions.value.find((b) => b.value == r.brand)?.label
        r.camSubtypeName = subtypeOptions.value.find((s) => s.value == r.camSubtype)?.label
        r.nvrSubtypeName = subtypeOptions.value.find((s) => s.value == r.nvrSubtype)?.label

        return r
      })
  })
  loading.value = false
}

const setCam = async (data) => {
  if (dialogOpenType.value === '添加') await insertCam(data)
  else if (dialogOpenType.value === '编辑') await updateCam(data)
  getCams()
}

const removeCam = async (item) => {
  await deleteCam({
    id: item.id
  })

  getCams()
}

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      setCam(dialogData.value)

      dialogFormVisible.value = false
    } else {
      console.log('验证失败!')
      return false
    }
  })
}

onMounted(() => {
  getGroups()
  getCams()
})
</script>

<template>
  <div class="container" v-loading="loading" element-loading-text="加载中...">
    <div class="group-box">
      <el-button class="add-button" type="info" plain @click="openGroupDialog()">
        添加分组
      </el-button>
      <el-dialog v-model="groupDialogFormVisible" :title="groupDialogOpenType" center width="450px">
        <el-form
          ref="groupRuleFormRef"
          :model="groupDialogData"
          :rules="groupRules"
          size="large"
          label-width="auto"
          class="w-full el-form-box"
        >
          <el-form-item label="分组名" prop="name">
            <el-input v-model="groupDialogData.name" placeholder="分组名" style="width: 200px" />
          </el-form-item>
          <el-form-item label="上级分组" prop="pid">
            <el-tree-select
              v-model="groupDialogData.pid"
              :data="groupsData"
              :props="{ value: 'id', label: 'name' }"
              check-strictly
              placeholder="上级分组"
              style="width: 200px"
            >
            </el-tree-select>
          </el-form-item>
          <el-form-item>
            <el-button
              class="submit-button"
              type="primary"
              @click="groupSubmitForm(groupRuleFormRef)"
            >
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <el-tree
        :data="groupsData"
        node-key="id"
        :props="{ label: 'name' }"
        default-expand-all
      >
        <template #default="{ node, data }">
          <span style="font-size: 16px">{{ node.label }}</span>
          <el-icon :size="15" color="#0aa" style="margin-left: 10px">
            <Edit @click="openGroupDialog(data)" />
          </el-icon>
          <el-popconfirm title="确定删除？" @confirm="removeGroup(data)">
            <template #reference>
              <el-icon :size="15" color="#f00">
                <Close />
              </el-icon>
            </template>
          </el-popconfirm>
        </template>
      </el-tree>
    </div>
    <div>
      <el-button class="add-button" plain type="info" @click="openDialogByInsert"
        >添加设备</el-button
      >
      <SytTable :columns="tableThs" :data="tableData">
        <template #operations="scope">
          <el-button
            size="small"
            type="primary"
            @click="openDialogByEdit(scope.row)"
            icon="Edit"
            circle
          />
          <el-popconfirm
            :title="`确定删除?`"
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="InfoFilled"
            icon-color="var(--el-color-warning)"
            @confirm="removeCam(scope.row)"
          >
            <template #reference>
              <el-button size="small" type="danger" icon="Delete" circle />
            </template>
          </el-popconfirm>
        </template>
      </SytTable>
      <el-dialog v-model="dialogFormVisible" :title="dialogOpenType" center>
        <el-form
          ref="ruleFormRef"
          :model="dialogData"
          :rules="rules"
          size="large"
          label-width="auto"
          class="w-full el-form-box"
        >
          <el-form-item label="设备名" prop="name">
            <el-input v-model="dialogData.name" placeholder="设备名" />
          </el-form-item>
          <el-form-item label="摄像机品牌" prop="brand">
            <el-select v-model="dialogData.brand" placeholder="摄像机品牌" style="width: 200px">
              <el-option
                v-for="item in brandOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分组" prop="group">
            <el-tree-select
              v-model="dialogData.group"
              :data="groupsData"
              :props="{ value: 'id', label: 'name' }"
              check-strictly
              placeholder="分组"
              style="width: 200px"
            >
            </el-tree-select>
          </el-form-item>
          <el-form-item label="摄像机ip地址" prop="camIp">
            <el-input v-model="dialogData.camIp" placeholder="摄像机ip地址" />
          </el-form-item>
          <el-form-item label="摄像机账号" prop="camUsername">
            <el-input v-model="dialogData.camUsername" placeholder="摄像机账号" />
          </el-form-item>
          <el-form-item label="摄像机密码" prop="camPassword">
            <el-input v-model="dialogData.camPassword" placeholder="摄像机密码" />
          </el-form-item>
          <el-form-item label="摄像机通道" prop="camChannel">
            <el-input-number
              v-model="dialogData.camChannel"
              placeholder="摄像机通道"
              :min="1"
              :precision="0"
              controls-position="right"
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item label="摄像机码流" prop="camSubtype">
            <el-select
              v-model="dialogData.camSubtype"
              placeholder="摄像机码流"
              style="width: 150px"
            >
              <el-option
                v-for="item in subtypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="录像机ip地址" prop="nvrIp">
            <el-input v-model="dialogData.nvrIp" placeholder="录像机ip地址" />
          </el-form-item>
          <el-form-item label="录像机账号" prop="nvrUsername">
            <el-input v-model="dialogData.nvrUsername" placeholder="录像机账号" />
          </el-form-item>
          <el-form-item label="录像机密码" prop="nvrPassword">
            <el-input v-model="dialogData.nvrPassword" placeholder="录像机密码" />
          </el-form-item>
          <el-form-item label="录像机通道" prop="nvrChannel">
            <el-input-number
              v-model="dialogData.nvrChannel"
              placeholder="录像机通道"
              :min="1"
              :precision="0"
              controls-position="right"
              style="width: 100px"
            />
          </el-form-item>
          <el-form-item label="录像机码流" prop="nvrSubtype">
            <el-select
              v-model="dialogData.nvrSubtype"
              placeholder="录像机码流"
              style="width: 150px"
            >
              <el-option
                v-for="item in subtypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="submit-button" type="primary" @click="submitForm(ruleFormRef)">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.container {
  height: 100%;
  display: flex;
  align-items: start;
}

.container > * {
  margin: 10px;
}

.group-box {
  width: 220px;
  height: 100%;
  margin-right: 10px;
  border-right: 1px solid rgb(0 0 0 / 0.1);
  overflow: scroll;
}

.add-button {
  margin-bottom: 10px;
}

.submit-button {
  width: 150px;
  margin: 0 auto;
}

.el-form-box {
  box-sizing: border-box;
  padding: 10px 50px;
}
</style>
